<template>
  <view class="container" style="background: #FFF;min-height: 100%;">
    <!-- 搜索框 -->
    <uni-row>
      <uni-col :span="20">
        <uni-search-bar class="uni-mt-10" radius="5" placeholder="请输入车牌号" clearButton="auto" cancelButton="none"  @confirm="query()" @cancel="cancel" v-model="searchParam.searchValue" />
      </uni-col>
      <uni-col :span="4" >
        <div class="tire-center" @click="showDrawer()" style="width: 100%;height: 100%">筛选</div>
      </uni-col>
    </uni-row>

    <uni-segmented-control
      :current="activeTab"
      :values="tabList.map(item => item.label)"
      @clickItem="handleTabClick"
      styleType="text"
      activeColor="#fc4b01"
    />

    <view v-if="releaseRecordsList.length === 0" style="border-top: 1px solid #dcdcdc">
      <image src="/static/nodata.png" style="width: 100%"></image>
    </view>

    <!-- 渲染存储记录 -->
    <view style="border-top: 1px solid #dcdcdc">
      <uni-card v-for="(item, index) in releaseRecordsList" :title="findById(item.storeId,selectData.storeList)?.text" :extra="formatDate(item.createTime)+' 创建'" @click="openReleaserecordsDetail(item.id,'update')">
        <uni-row>
          <uni-col :span="24" style="text-align: left;">存储车牌：{{ item.licensePlate }}</uni-col>
          <uni-col :span="24" style="text-align: left;">联系电话：{{ item.contactNumber }}</uni-col>
        </uni-row>
        <uni-row>
          <uni-col :span="12" style="text-align: left;">存储类型：{{ getCodeText(item.storageType,selectData.storageTypeList) }}</uni-col>
          <uni-col :span="12" style="text-align: left;">
            存储状态：
            <uni-tag :text="getCodeText(item.status,selectData.statusList)" :type="getTagType(item.status)" size="mini"/>
          </uni-col>
        </uni-row>
      </uni-card>
    </view>
  </view>

  <!-- 右侧抽屉 -->
  <uni-drawer ref="showRight" mode="right" :mask-click="false">
    <view class="scroll-view">
      <scroll-view class="scroll-view-box" scroll-y="true">
        <button type="warn" @click="closeDrawer()"><text class="word-btn-white">关闭筛选</text></button>
        <view class="info-content">
          <uni-section title="选择门店" type="line">
            <uni-data-select v-model="selectedStoreId" :localdata="selectData.storeList"></uni-data-select>
          </uni-section>
        </view>
        <view class="close">
          <button class="drawer-btn" @click="resetFilter"><text class="word-btn-white">重置</text></button>
          <button  class="drawer-btn" type="primary" @click="confirm()"><text class="word-btn-white">确定</text></button>
        </view>
      </scroll-view>
    </view>
  </uni-drawer>
</template>

<script lang="ts">
  import { ReleaseRecordsApi, ReleaseRecordsVO } from '@/sheep/api/releaserecords';
  import { DictUtils } from '@/sheep/store/DictUtils';
  import { StoreApi } from '@/sheep/api/store';
  import { DepositRecordsApi } from '@/sheep/api/depositrecords';

  export default {
    components: {},
    data() {
      return {
        selectData:{
          statusList:[],
          storageTypeList:[],
          storeList:[]
        },
        tabList: [
          { status: [1,2,3,4], label: '全部' },
          { status: '1', label: '已预约' },
          { status: '2', label: '已接单' },
          { status: '3', label: '已出库' },
          { status: '4', label: '已完成' },
        ],
        searchParam:{
          pageNo:1,
          storeId:"",
          searchValue: "",
          status:[1,2,3,4],
          warehouseId:uni.getStorageSync('warehouseId')
        },
        releaseRecordsList: [] as ReleaseRecordsVO[],
        selectedStoreId: "", // 选中的门店
        showRight: false,
      };
    },
    onLoad: function (options) {
      this.initSelectData();
    },
    onShow() {
      this.query();
    },
    onPullDownRefresh() {
      this.query();
      setTimeout(function () {
        uni.stopPullDownRefresh();
      }, 1000);
    },
    onReachBottom(){
      this.query(++this.searchParam.pageNo);
    },
    methods: {
      handleTabClick(e) {
        this.searchParam.status = this.tabList[e.currentIndex].status;
        this.query();
      },
      // 点击 FAB 按钮时跳转到详情页
      openReleaserecordsDetail(id: string,type: string = "create") {
        // 初始化一个参数对象，id 必须存在
        const params = { type };

        // 如果 id 为空，则不执行跳转
        if (!(!id || id === 'null' || id === 'undefined')) {
          params.id = id
        }

        // 构建查询字符串
        const queryString = Object.entries(params)
          .map(([key, value]) => `${key}=${encodeURIComponent(value)}`)
          .join('&');

        // 跳转到目标页面
        uni.navigateTo({
          url: `/pages/releaserecords/releaserecordsDetail?${queryString}`
        });
      },
      // 获取存储记录列表
      async query(pageNo?:number) {
        if(pageNo){
          this.searchParam.pageNo = pageNo;
        }else{
          this.searchParam.pageNo = 1;
        }
        try {
          const { data } = await ReleaseRecordsApi.getReleaseRecordsPage({licensePlate:this.searchParam.searchValue,...this.searchParam});
          const { list } = data;

          // 如果是第一页，直接赋值，否则推入新数据
          if (this.searchParam?.pageNo === 1) {
            this.releaseRecordsList = list;
          } else {
            this.releaseRecordsList.push(...list);
          }
        } catch (error) {
          console.error('Failed to fetch release records:', error);
        }
      },
      // 清空搜索值并重新加载记录
      cancel() {
        this.searchParam.searchValue = "";
        this.query();
      },
      // 格式化时间
      formatDate(date: string) {
        const d = new Date(date);
        const pad = (num: number) => String(num).padStart(2, "0");

        return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
      },
      getCodeText(status: string,codeList:[]) {
        const item = codeList.find(item=>item.value==status);
        return item?.label || '未知';
      },
      getTagType(status: number){
        switch (status) {
          case 1:return "primary";
          case 2:return "success";
          case 3:return "warning";
          case 4:return "error";
          default:return "";
        }
      },
      findById(id: string,list:[]):any {
        const item = list.find(item=>item.value==id);
        return item;
      },
      async initSelectData() {
        this.selectData.statusList = DictUtils.getDictData('tire_release_records_status');
        this.selectData.storageTypeList = DictUtils.getDictData('tire_storage_type');

        const storeResult = await StoreApi.getStorePage({});
        this.selectData.storeList = await this.buildSelectData(storeResult?.data?.list || [], 'storeName');
      },
      async buildSelectData(list: any[], name: string) {
        return list.map(item => ({
          value: item['id'],
          text: item[name]
        }));
      },
      resetFilter(){
        this.selectedStoreId = '';
      },
      confirm() {
        this.searchParam.storeId = this.selectedStoreId;
        this.query(1);
        this.$refs['showRight'].close()
      },
      // 打开窗口
      showDrawer() {
        this.$refs['showRight'].open()
      },
      // 关闭窗口
      closeDrawer() {
        this.$refs['showRight'].close()
      },
    },
    onNavigationBarButtonTap(e) {
      this.$refs.showRight.open()
    },
    // app端拦截返回事件 ，仅app端生效
    onBackPress() {
      if (this.showRight) {
        this.$refs.showRight.close()
        return true
      }
    }
  };
</script>


<style lang="scss">
  .example-body {
    padding: 10px;
  }
  .scroll-view {
    /* #ifndef APP-NVUE */
    width: 100%;
    height: 100%;
    /* #endif */
    flex:1
  }
  // 处理抽屉内容滚动
  .scroll-view-box {
    flex: 1;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
  }
  .info {
    padding: 15px;
    color: #666;
  }

  .info-text {
    font-size: 14px;
    color: #666;
  }
  .info-content {
    padding: 5px 15px;
  }
  .close {
    display: flex;
    justify-content: space-between; // 或者 `justify-content: center;`
    width: 100%;
    position: absolute;
    bottom: 0;
    left: 0;
    background: #fff;
    padding: 10px;
  }

  .drawer-btn {
    flex: 1;  // 让按钮平均分布
    margin: 0; // 按钮之间有间距
    text-align: center;
    width: 49%;
  }


  .tire-center {
    display: flex;
    justify-content: center; // 水平居中
    align-items: center; // 垂直居中
    margin: 30rpx auto 0; /* 上间距和自动水平居中 */
  }
</style>
